<template>
	<view class="selelctBlessingWays">
		<!-- <uni-nav-bar left-icon="back" statusBar class="navbarHeight" @clickLeft="goSettlementPage" title="祝福形式"></uni-nav-bar> -->
		<view class="selectBless">
			<view class="view_position">
				<view class="box" @click="goBlessingPage(2)">
					<view class="select_audio">
						<image class="slect_pic" src="https://safood.supplyocta.com/Public/MallSmallApp/audio_select.png" mode="aspectFit"></image>
						<text>选择音频</text>
					</view>
					<view class="entry">
						选择
					</view>
				</view>
				<view class="box" @click="goBlessingPage(1)" style="margin-top:40rpx">
					<view class="select_audio">
						<image class="slect_pic" src="https://safood.supplyocta.com/Public/MallSmallApp/video_select.png"></image>
						<text>选择视频</text>
					</view>
					<view class="entry">
						选择
					</view>
				</view>
			</view>
			<!-- 		<view class="btnPostion">
					<view v-if="blessData.saveName" @click="goSettlementPage" class="circle_btn">
						<uni-icons type="checkmarkempty" size="15" color="#fff"></uni-icons>
						已完成返回上级</view>
				</view> -->
			<view v-if="_type==2 && isLoading" class="luzhi_style">
				<block>
					录制中<span class="loading">...</span>
				</block>
			</view>
			<!-- 底部音频选择框 -->
			<view class="audio_select" v-if="select_audio">
				<view style="display: flex;justify-content: flex-end;width:90%" @click="cancelAudio">
					<uni-icons type="closeempty" size="20" color="#666"></uni-icons>
				</view>
				<view class="record_audio" style="magrin:0" @click="startRecord">
					<view class="flex-al-cen">
						<image class="audio_icon" src="/static/images/record_audio.png" mode=""></image>
						<text>{{isLoading?'停止录音':'录音'}}</text>
					</view>
				</view>
				<!-- #ifdef MP-WEIXIN -->
				<view class="record_audio" style="margin-bottom: 40rpx;" @click="selectAudio">
					<view class="flex-al-cen">
						<image class="audio_icon" src="/static/images/upload_audio.png" mode=""></image>
						<text>上传音频</text>
					</view>
				</view>
				<!-- #endif -->

			</view>

		</view>
		<view class="bg" :style="{display:isdisplay}"></view>
	</view>
</template>

<script>
	// #ifdef MP-WEIXIN
	const recorderManager = uni.getRecorderManager();
	// #endif
	// #ifdef MP-ALIPAY
	const recorderManager = my.getRecorderManager();
	// #endif
	const innerAudioContext = uni.createInnerAudioContext();
	var app = getApp().globalData;

	import {
		uploadVideo
	} from '@/utils/uploadvideo.js'
	
	export default {
		data() {
			return {
				blessData: {

				},
				video_tmp_src: '',
				audio_tmp_src: '',
				tmpSrc: '', // 正式路径
				_type: 1, // 1为视频  2为音频
				audio_length: '',
				dataInfo: {
					storage_type: '',
					savename: ''
				},
				select_audio: false,
				isLoading: false,
				isdisplay: 'none'
			}
		},
		onLoad(options) {
			console.log(options)
			let blessData = options.blessData
			if (blessData) {
				blessData = JSON.parse(blessData)
				if (blessData.flag == 'isEdit') {
					this.blessData = blessData
					if (blessData.type == 1) {
						this.video_tmp_src = blessData.address
					} else {
						this.audio_tmp_src = blessData.address
					}
					this.$set(this.dataInfo, 'savename', blessData.url)
					this.$set(this.dataInfo, 'storage_type', blessData.storageType)
				}
			}
			let self = this;
			recorderManager.onStop(function(res) {
				console.log('recorder stop' + JSON.stringify(res));
				console.log(res.tempFilePath, 'ddddddddddddddddd')
				self.audio_tmp_src = res.tempFilePath;
				self.submitBlessing(2)
			});

		},
		onUnload() {},
		onShow() {
			this.videoShow = false
			let blessData = uni.getStorageSync('blessData')
			if (blessData && blessData.flag == 'isAdd') {
				this.blessData = JSON.parse(blessData)
			}

		},
		methods: {
			goBlessingPage(type) {
				let _this = this
				this._type = type
				// 1为视频  2为音频
				if (type == 1) {
					_this.videoUpload()
				} else {
					this.isdisplay = 'block'
					this.select_audio = true
				}
				// uni.navigateTo({
				// 	url: `../blessingPage/blessingPage?blessData=${JSON.stringify(_this.blessData)}&isVoice=${type}`
				// })
			},
			goSettlementPage() {
				let goods_ids = uni.getStorageSync('shopping_ids')
				uni.navigateBack({
					delta: 1
				});
			},

			// 视频上传
			videoUpload: function() {
				var self = this;
				uni.chooseVideo({
					count: 1,
					compressed: false,
					sourceType: ['camera', 'album'],
					success: function(res) {
						if (res.errMsg == 'chooseVideo:ok') {
							self.video_tmp_src = res.tempFilePath;
							self.submitBlessing(1)
						}
					}
				});
			},

			// 取消音频
			cancelAudio() {
				this.isdisplay = 'none';
				this.select_audio = false
			},

			//选择音频
			selectAudio() {
				let _this = this
				// #ifdef MP-WEIXIN
				wx.chooseMessageFile({
					success: function(res) {
						if (res.errMsg == 'chooseMessageFile:ok') {
							let tempFiles = Object.assign({}, res.tempFiles[0])
							if (tempFiles.type == 'video') {
								uni.showToast({
									title: '该文件为MP4格式,请通过上传视频方式上传',
									icon: 'none'
								})
								return;
							}
							// tempFiles.time = format_time(tempFiles.time)
							_this.dataInfo = Object.assign({}, tempFiles)
							_this.$set(_this.dataInfo, 'name', tempFiles.name)
							_this.audio_tmp_src = tempFiles.path
							_this.submitBlessing(2)
						}
					}
				})
				// #endif
			},

			// 开始录音
			async startRecord() {
				if (!this.isLoading) {
					console.log('开始录音');
					this.isLoading = true
					const options = {
						duration: 60000, //指定录音的时长，单位 ms，最大为10分钟（600000），默认为1分钟（60000）
						sampleRate: 16000, //采样率
						numberOfChannels: 1, //录音通道数
						encodeBitRate: 96000, //编码码率
						format: 'mp3', //音频格式，有效值 aac/mp3
						frameSize: 50, //指定帧大小，单位 KB
					}
					recorderManager.start(options);
				} else {
					this.isLoading = false
					await recorderManager.stop();
				}

			},

			/// 保存语音/视频
			submitBlessing(type) {
				this._type = type
				uni.showLoading({
					title: '正在上传中...'
				})
				let self = this
				let baseUrl = getApp().globalData.XcxData.siteBaseUrl
				uploadVideo({
					url: `/Blessing/Applets/uploadBlessing`,
					fileType: type == 2 ? 'audio' : 'video',
					path: type == 2 ? self.audio_tmp_src : self.video_tmp_src,
					formData: {},
					name: 'file',
					method: "POST",
				}, self.callback)
			
			},
			async callback(res) {
				console.warn(res)
				if (res.status == 0) {
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
					return;
				}
				if (res.length == 0) {
					uni.showToast({
						title: '上传内容太大,请重新上传',
						icon: 'none'
					})
					return;
				}
				let {
					access_path,
					storage_type,
					savepath,
					path_name,
					size,
					ext,
					saveName
				} = res.file
				let _path = access_path
				if ((this.audio_tmp_src || this.video_tmp_src) && this.blessData && this.blessData.flag ==
					'isEdit') {
					await this.deleteItem(this._type, this._type, false)
				}
				if ((ext == 'mp3' || 'm4a' || 'wma' || 'MP3') && this._type == 2) {
					this.audio_tmp_src = _path
				} else {
					this.video_tmp_src = _path
				}
				this.tmpSrc = _path
				this.dataInfo = {
					storage_type,
					savename: storage_type == 1 ? path_name : saveName
				}
				let params = {
					flag: this.blessData.orderId ? 'isEdit' : 'isAdd',
					type: this._type,
					url: this.dataInfo.savename,
					storageType: storage_type,
					address: _path,
					audio_length: this.audio_length ? this.audio_length : '',
					ext: ext,
				}
				if (this.blessData.orderId) {
					let _params = {
						orderId: this.blessData.orderId,
						type: this._type,
						url: this.dataInfo.savename,
						storageType: storage_type,
						address: _path,
						ext: ext,
					}
					const {
						status,
						message,
						data
					} = await this.$request('Blessing/Applets/blessingSave', _params)
					console.log(_params, '_params')
					console.log(status, 'save')
					if (status == 1) {
						uni.showToast({
							title: message
						})
						_params = Object.assign({
							flag: 'isEdit',
							audio_length: this.audio_length ? this.audio_length : '',
						}, _params)
						uni.setStorageSync('blessData', JSON.stringify(_params))
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							})
						}, 500)
						return;
					} else {
						uni.showToast({
							title: message,
							icon: 'none'
						})
					}
				} else {
					uni.setStorageSync('blessData', JSON.stringify(params))
				}
				uni.hideLoading()
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					})
				}, 500)
			},


			// 删除
			async deleteItem(type, isVoice, isShowTip = true) {
				if ((type == 2 && isVoice == 2) || (type == 1) && isVoice == 1) {
					let obj = {
						storage_type: this.dataInfo.storage_type,
						url: this.dataInfo.savename
					}
					try {
						const res = await this.$request('Blessing/Applets/deleteBlessing', obj)
						if (res.status == 1) {
							if (isShowTip) {
								uni.showToast({
									title: '删除成功',
								})
							}
							if (type == 2) {
								this.audio_tmp_src = '';
							} else {
								this.video_tmp_src = '';
							}
							this.tmpSrc = '';
						}
						uni.removeStorageSync('blessData')
					} catch (err) {
						console.log(err)
					}
				}
			}

		}
	}
</script>

<style lang="scss" scoped>
	@import './selectBlessingWays.scss'
</style>
